<template>
  <div class="container search-page">
    <div class="search-header">
      <h1 class="search-title">搜索结果: "{{ keyword }}"</h1>
      <p v-if="total > 0" class="search-stats">共找到 {{ total }} 篇相关文章</p>
      <p v-else class="search-stats">未找到相关文章</p>
    </div>

    <div class="search-container">
      <el-input
        v-model="searchText"
        placeholder="输入关键词搜索..."
        class="search-input"
        @keyup.enter="handleSearch"
      >
        <template #suffix>
          <el-icon class="search-icon" @click="handleSearch">
            <Search />
          </el-icon>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果列表 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    <div v-else-if="articles.length > 0" class="search-results">
      <div v-for="article in articles" :key="article.id" class="search-result-item">
        <router-link :to="`/article_detail?id=${article.id}`" class="article-link">
          <div class="article-thumb">
            <img
              v-if="article.thumbnail?.trim().length > 0"
              :src="article.thumbnail"
              :alt="article.title"
            />
            <img v-else src="@/assets/images/zhanwei.jpg" :alt="article.title" />
          </div>
          <div class="article-content">
            <h2 class="article-title" v-html="highlightKeyword(article.title, keyword)"></h2>
            <p class="article-summary" v-html="highlightKeyword(article.summary, keyword)"></p>
            <div class="article-meta">
              <span class="meta-item">
                <i class="fa fa-user"></i>
                {{ article.updatedName }}
              </span>
              <span class="meta-item">
                <i class="fa fa-calendar"></i>
                {{ formatDateUnique(article.createTime) }}
              </span>
              <span class="meta-item">
                <i class="fa fa-eye"></i>
                {{ article.viewCount }} 阅读
              </span>
            </div>
          </div>
        </router-link>
      </div>
    </div>
    <div v-else class="no-results">
      <div class="no-results-content">
        <i class="fa fa-search-minus no-results-icon"></i>
        <h3>没有找到与 "{{ keyword }}" 相关的文章</h3>
        <p>请尝试其他关键词，或浏览以下推荐内容</p>
      </div>

      <!-- 推荐内容 -->
      <div v-if="recommendedArticles.length > 0" class="recommended-content">
        <h4 class="recommended-title">推荐阅读</h4>
        <div class="recommended-list">
          <div v-for="article in recommendedArticles" :key="article.id" class="recommended-item">
            <router-link :to="`/article_detail?id=${article.id}`">
              {{ article.title }}
            </router-link>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="pageRequest.pageNum"
      v-model:limit="pageRequest.pageSize"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import ArticleApi, { LzArticlePageVO } from "@/api/content/lz-article";
import { formatDateUnique } from "@/utils/formatterUtils";
import { Search } from "@element-plus/icons-vue";

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const total = ref(0);
const articles = ref<LzArticlePageVO[]>([]);
const recommendedArticles = ref<LzArticlePageVO[]>([]);
const searchText = ref("");

// 从URL获取关键词
const keyword = computed(() => route.query.keyword?.toString() || "");

// 分页请求参数
const pageRequest = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
});

// 监听路由变化
watch(
  () => route.query.keyword,
  (newKeyword) => {
    if (newKeyword) {
      searchText.value = newKeyword.toString();
      pageRequest.value.keyword = newKeyword.toString();
      fetchSearchResults();
    }
  },
  { immediate: true }
);

// 监听分页变化
watch(
  () => pageRequest.value,
  () => {
    fetchSearchResults();
  },
  { deep: true }
);

// 搜索处理
const handleSearch = () => {
  if (!searchText.value.trim()) return;

  router.push({
    path: "/search",
    query: {
      keyword: searchText.value.trim(),
    },
  });
};

// 获取搜索结果
const fetchSearchResults = async () => {
  if (!pageRequest.value.keyword) return;

  try {
    loading.value = true;
    // 假设ArticleApi.search是搜索API
    const response = await ArticleApi.getPage({
      ...pageRequest.value,
      keyword: pageRequest.value.keyword,
    });

    articles.value = response.list;
    total.value = response.total;

    // 如果没有结果，获取推荐内容
    if (response.total === 0) {
      fetchRecommendedArticles();
    }
  } catch (error) {
    console.error("搜索失败:", error);
  } finally {
    loading.value = false;
  }
};

// 获取推荐文章
const fetchRecommendedArticles = async () => {
  try {
    const response = await ArticleApi.getPage({
      pageNum: 1,
      pageSize: 5,
    });
    recommendedArticles.value = response.list;
  } catch (error) {
    console.error("获取推荐文章失败:", error);
  }
};

// 高亮关键词
const highlightKeyword = (text: string, keyword: string) => {
  if (!keyword || !text) return text;
  const regex = new RegExp(`(${keyword})`, "gi");
  return text.replace(regex, '<span class="highlight-keyword">$1</span>');
};
</script>

<style lang="scss" scoped>
.search-page {
  padding: 30px 15px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-header {
  margin-bottom: 20px;

  .search-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #333;
  }

  .search-stats {
    font-size: 14px;
    color: #666;
  }
}

.search-container {
  margin-bottom: 30px;

  .search-input {
    max-width: 600px;

    :deep(.el-input__wrapper) {
      background: #f5f5f5;
      border-radius: 8px;
      padding: 0 15px;

      &:hover,
      &:focus-within {
        background: #fff;
        box-shadow: 0 0 0 1px #ffd700 !important;
      }
    }

    .search-icon {
      cursor: pointer;
      color: #666;

      &:hover {
        color: #ffd700;
      }
    }
  }
}

.search-results {
  .search-result-item {
    margin-bottom: 25px;
    border-bottom: 1px solid #eee;
    padding-bottom: 25px;

    &:last-child {
      border-bottom: none;
    }

    .article-link {
      display: flex;
      text-decoration: none;
      color: inherit;

      @media (max-width: 768px) {
        flex-direction: column;
      }

      &:hover {
        .article-title {
          color: #ffd700;
        }
      }
    }

    .article-thumb {
      flex: 0 0 200px;
      height: 140px;
      margin-right: 20px;
      border-radius: 8px;
      overflow: hidden;

      @media (max-width: 768px) {
        margin-right: 0;
        margin-bottom: 15px;
        height: 180px;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    .article-content {
      flex: 1;
    }

    .article-title {
      font-size: 18px;
      font-weight: 600;
      margin-bottom: 10px;
      color: #333;
      transition: color 0.3s;
    }

    .article-summary {
      font-size: 14px;
      color: #666;
      margin-bottom: 15px;
      line-height: 1.6;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .article-meta {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      font-size: 13px;
      color: #999;

      .meta-item {
        display: flex;
        align-items: center;

        i {
          margin-right: 5px;
        }
      }
    }
  }
}

.no-results {
  margin-top: 40px;
  text-align: center;

  .no-results-content {
    padding: 30px;
    margin-bottom: 30px;

    .no-results-icon {
      font-size: 48px;
      color: #ddd;
      margin-bottom: 20px;
    }

    h3 {
      font-size: 18px;
      margin-bottom: 10px;
      color: #333;
    }

    p {
      color: #666;
    }
  }

  .recommended-content {
    padding: 20px;
    background: #f9f9f9;
    border-radius: 8px;
    max-width: 800px;
    margin: 0 auto;

    .recommended-title {
      font-size: 16px;
      color: #333;
      margin-bottom: 15px;
      text-align: left;
    }

    .recommended-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 15px;

      .recommended-item {
        text-align: left;

        a {
          color: #555;
          text-decoration: none;
          display: block;
          padding: 8px 0;

          &:hover {
            color: #ffd700;
          }

          &::before {
            content: "•";
            margin-right: 8px;
            color: #ffd700;
          }
        }
      }
    }
  }
}

.loading-container {
  padding: 20px 0;
}

:deep(.highlight-keyword) {
  color: #ffd700;
  font-weight: bold;
  background: rgba(255, 215, 0, 0.1);
  padding: 0 2px;
}
</style>
